package com.iot.north.app.demo.invoke.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.iot.north.app.demo.domain.ResultDTO;
import com.iot.north.app.demo.exception.ResultCode;
import com.iot.north.app.demo.invoke.constant.AuthConstant;
import com.iot.north.app.demo.invoke.constant.RestConstant;
import com.iot.north.app.demo.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/** 此为调用api接口模块。 用户可以借鉴此demo，进行基于接口调用的开发。 */
@Service
@Slf4j
public class DeviceService {

  /** 调用添加设备api */
  public ResultDTO addDevice(String pk, String devId, String name) {
    HTTPClient httpClient = new HTTPClient();
    // 请求url
    String path = RestConstant.ADD_DEVICE;
    // 计算token
    String token = null;
    try {
      token =
          TokenUtil.assembleToken(
              path,
              String.valueOf(System.currentTimeMillis()),
              AuthConstant.ACCESS_KEY,
              AuthConstant.ACCESS_KEY_SECRET);
    } catch (Exception e) {
      e.printStackTrace();
      log.error(e.getMessage());
    }
    // header组建
    Map<String, String> headerParams = new HashMap<>();
    headerParams.put("Content-Type", "application/json");
    headerParams.put("Authorization", token);
    // body组建
    Map<String, Object> bodyParams = new HashMap<>();
    bodyParams.put("pk", pk);
    bodyParams.put("devId", devId);
    bodyParams.put("name", name);
    // 调用post请求
    JsonNode post = httpClient.post(RestConstant.BASE_URL + path, headerParams, bodyParams);
    log.info("the response is: " + post);
    return new ResultDTO(
        post.get("code") != null
            ? post.get("code").asText()
            : String.valueOf(ResultCode.SUCCES.getCode()),
        post.get("msg") != null
            ? post.get("msg").asText()
            : String.valueOf(ResultCode.SUCCES.getMsg()));
  }
}
